<template>
  <BasicModal v-bind="$attrs" @register="registerNoticeModal" title="流程通知设置" @ok="handleSubmit" width="700px">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { getNoticeWayList, getFlowNotice, saveFlowNotify } from '../design.api';
  import { noticeFromSchema, noticeTypeOptions } from '../design.data';
  // Emits声明
  const emit = defineEmits(['register','success']);
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 100,
    schemas: noticeFromSchema,
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerNoticeModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false });
    //获取详情
    data = await getFlowNotice({ id: data.id });
    if(data){
      const ntpys = [];
      noticeTypeOptions.forEach((item) => {
         if(data[item.value] == '1'){
          ntpys.push(item.value);
         }
      });
      data.noticeTypes = ntpys;
      //表单赋值
      await setFieldsValue({
        ...data,
      });
    }
  });

  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      const noticeTypeChecedList = values.noticeTypes.split(",");
      noticeTypeOptions.forEach((item) => {
        values[item.value] = noticeTypeChecedList.indexOf(item.value) > -1 ? '1' : '0';
      });
      delete values.noticeTypes;
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveFlowNotify(values);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
